import { _decorator, Component, Sprite, Node, SpriteFrame, v3, Color, UITransform, EventTouch, Vec3, log } from 'cc';
const { ccclass, property } = _decorator;

import { Consts } from "../Data/Consts";
import { bdlMgr } from "../Manager/SS_BundleManager";
import CardFunctions from '../Common/CardFunctions';
import { GameData } from '../Data/GameData';
import CommonFunction from '../utils/CommonFunction';
import SS_Line from './SS_Line';
import SS_NodeManager from '../Manager/SS_NodeManager';
import Grid from './Grid';
import SS_GameManager from '../Manager/SS_GameManager';
import { GameState } from '../Data/GameEnum';

// /**卡片 */
@ccclass('Card')
export default class Card extends Component {
    @property({ type: Sprite })
    public Sprite_bg: Sprite | null = null;
    @property({ type: Sprite })
    public Sprite_icon: Sprite | null = null;
    @property({ type: Node })
    public cover: Node | null = null;
    @property({ type: Sprite })
    public Sprite_frame: Sprite | null = null;

    id = 0;
    col = 0;
    row = 0;

    onLoad() {
    }

    Init(_col, _row, _id) {
        this.id = _id;
        this.col = _col;
        this.row = _row;

        this.InitWidthAndHeight(GameData.cell_width, GameData.cell_height);
        this.InitPosition();

        this.Refresh();
        this.AddListener();
    }

    Refresh() {
        this.RefreshIcon();
    }

    async RefreshIcon() {
        this.Sprite_icon.node.active = true;

        this.Sprite_icon.node.active = true;

        bdlMgr.getRes<SpriteFrame>(Consts.BundleName.SPRITE, `main/item/${this.id}/spriteFrame`, SpriteFrame).then(res => { this.Sprite_icon.spriteFrame = res });

        this.Sprite_icon.sizeMode = Sprite.SizeMode.TRIMMED;
        this.Sprite_icon.node.scale = v3(0.5, 0.5, 0.5);
    }

    InitWidthAndHeight(cardWidth?: number, cardHeight?: number) {
        if (cardWidth) this.node.getComponent(UITransform).width = cardWidth;
        if (cardHeight) this.node.getComponent(UITransform).height = cardHeight;
    }

    InitPosition() {
        let x = CardFunctions.Get_x_by_col(this.col);
        let y = CardFunctions.Get_y_by_row(this.row);
        this.node.setPosition(x, y, 0);
    }

    async Refresh2() {
    }

    AddListener() {
        this.node.on(Node.EventType.TOUCH_START, this.TOUCH_START, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.TOUCH_MOVE, this);
        this.node.on(Node.EventType.TOUCH_END, this.TOUCH_END, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.TOUCH_END, this);
    }

    canMove: boolean = true;
    sibling;

    async TOUCH_START(event: EventTouch) {
        // console.log(`TOUCH_START`);

        this.node.getComponent(UITransform).priority = 1;

        if (!this.canMove) {
            return;
        }

        let pos1 = this.node.worldPosition;
        SS_Line.Instance.p_start = SS_Line.Instance.node.parent.getComponent(UITransform).convertToNodeSpaceAR(pos1);

        SS_NodeManager.Instance.隐藏Card.setPosition(SS_Line.Instance.p_start);

        CardFunctions.AllGridSelect(false);
        let grid1: Grid = CardFunctions.GetGrid(this.col, this.row)
        if (grid1) {
            grid1.Select(true);
            GameData.arrLines.push(grid1);
        }
    }

    TOUCH_MOVE(event: EventTouch) {
        // console.log(`TOUCH_MOVE`, this.col, this.row);

        if (!this.canMove) {
            return;
        }

        let pos = event.getUILocation();

        SS_NodeManager.Instance.隐藏Card.position = SS_NodeManager.Instance.隐藏Card.parent.getComponent(UITransform).convertToNodeSpaceAR(v3(pos.x, pos.y, 0));



        let grid = this.选中(event);
        this.是否满足(grid);

        // console.log(`选中`, grid);
        // if (grid) {
        //     let index = GameData.arrLines.indexOf(grid);
        //     if (index >= 0) {
        //         GameData.arrLines.splice(index + 1);
        //     }
        //     else {
        //         GameData.arrLines.push(grid);
        //     }
        // }
        // if (this.是否满足(grid)) {
        //     // GameData.arrLines.push(grid);
        // }
        // else {

        // }

        this.绘制线段();
    }

    是否满足(grid) {
        if (grid) {
            let index = GameData.arrLines.indexOf(grid);
            if (index >= 0) {
                GameData.arrLines.splice(index + 1);
            }
            else {
                let c = GameData.arrLines[GameData.arrLines.length - 1];
                let p = grid;
                let center = v3(c.x, c.y, 0);
                let point = v3(p.x, p.y, 0);
                let isInCenterGrid = CardFunctions.isInCenterGrid(point.x, point.y, center.x, center.y)

                let card1 = CardFunctions.GetCard(c.x, c.y);
                let card2 = CardFunctions.GetCard(p.x, p.y);
                let IsSameKind = CardFunctions.IsSameKind(card1.id, card2.id);
                if (isInCenterGrid && IsSameKind) {
                    GameData.arrLines.push(grid);

                    return true;
                }
            }
        }

        return false;
    }


    async TOUCH_END(t) {
        // console.log("TOUCH_END");

        if (GameData.arrLines && GameData.arrLines.length && GameData.arrLines.length >= 3) {
            SS_GameManager.Instance.gameState = GameState.三消开始;
            CardFunctions.MainLoop();
        }


        // if (GameData.arrLines && GameData.arrLines.length && GameData.arrLines.length >= 3) {
        //     //循环GameData.arrLine
        //     for (let i = 0; i < GameData.arrLines.length; i++) {
        //         let grid = GameData.arrLines[i];
        //         let card = CardFunctions.GetCard(grid.x, grid.y);
        //         if (card) {
        //             card.node.destroy();

        //         }
        //     }
        // }


        // GameData.arrLines = [];
        // SS_Line.Instance.g.clear();
    }

    选中(event) {
        CardFunctions.AllGridSelect(false);
        for (let x = 0; x < GameData.col; x++) {
            for (let y = 0; y < GameData.row; y++) {
                let grid = CardFunctions.GetGrid(x, y);
                let p1 = grid.node.worldPosition;
                let p2 = event.getUILocation();
                if (CardFunctions.判断是否在范围(p1, p2, 25)) {
                    grid.Select(true);

                    // let index = GameData.arrLines.indexOf(grid);
                    // if (index >= 0) {
                    // }
                    // else {
                    //     GameData.arrLines.push(grid);
                    // }

                    return grid;
                    break;
                }
            }
        }
    }

    绘制线段() {
        console.log("长度", GameData.arrLines.length);

        if (GameData.arrLines && GameData.arrLines.length && GameData.arrLines.length >= 2) {
            SS_Line.Instance.g.clear();
            SS_Line.Instance.g.lineWidth = 10;
            SS_Line.Instance.g.fillColor.fromHEX('#ff0000');

            let grid = GameData.arrLines[0];
            let p1 = grid.node.worldPosition;
            let p2 = SS_Line.Instance.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p1);
            SS_Line.Instance.g.moveTo(p2.x, p2.y);

            for (let i = 1; i < GameData.arrLines.length; i++) {
                let grid = GameData.arrLines[i];
                let p1 = grid.node.worldPosition;
                let p2 = SS_Line.Instance.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p1);
                SS_Line.Instance.g.lineTo(p2.x, p2.y);
            }
            SS_Line.Instance.g.stroke();
        }
        else {
            SS_Line.Instance.g.clear();
        }
    }
}